package com.cnbm.config;

import com.cnbm.common.constant.PackageConstant;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ApiKey;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.List;

import static com.google.common.collect.Lists.newArrayList;

/**
 * @Author weihongyang
 * @Date 2020/8/10 15:46
 * @Version 1.0
 */
@Configuration
@EnableSwagger2
@Profile({"dev","test"})
//@ConditionalOnProperty(name = "swagger.enable" , havingValue = "true")
public class SwaggerConfig implements WebMvcConfigurer {


    @Bean
    public Docket sysDocket(){
        return createRestApi("系统模块", PackageConstant.ADMIN_PACKAGES+".modules.sys","系统模块服务提供的 RestFul APIs");
    }

    @Bean
    public Docket opcUaDocket(){
        return createRestApi("OPCUA模块", PackageConstant.ADMIN_PACKAGES+".modules.opcua","OPCUA数据采集 RestFul APIs");
    }

    @Bean
    public Docket myDocket(){
        return createRestApi("MQ模块", PackageConstant.ADMIN_PACKAGES+".modules.messagequeue","MQ模块 RestFul APIs");
    }

    public Docket createRestApi(String groupName, String basePackage, String description) {
        return new Docket(DocumentationType.SWAGGER_2).groupName(groupName)
                .apiInfo(apiInfo(description))
                .select()
                //加了ApiOperation注解的类，才生成接口文档
//                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                //包下的类，才生成接口文档
                .apis(RequestHandlerSelectors.basePackage(basePackage))
                .paths(PathSelectors.any())
                .build()
                .securitySchemes(security());
    }

    private ApiInfo apiInfo(String description) {
        return new ApiInfoBuilder()
                .title("使用 Swagger2 构建的 RestFul APIs")
                .description(description)
                .termsOfServiceUrl("https://www.baidu.com")
                .version("3.0.0")
                .build();
    }

    private List<ApiKey> security() {
        return newArrayList(
                new ApiKey("token", "token", "header")
        );
    }
}